package org.dromara.web.plugins.search;


import com.alibaba.dashscope.protocol.okhttp.OkHttpHttpClient;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

@Component
@Slf4j
public class SearchComponent {

    @Autowired
    OkHttpClient okHttpClient;


    private static final String apiKey = "AIzaSyCmQMsy4VnhQScKu8YNCD_8tzS9_BzJnlc";
    private static final String searchFormat = "https://www.googleapis.com/customsearch/v1?key=%s&cx=%s&q=%s";
    private static final String cx = "1079b7f822b574f05";

    private static int searchResultsLimit = 10;



    public String networkSearch(String search) {

        Request request = new Request.Builder().url(String.format(searchFormat, apiKey, cx, search)).build();
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            ResponseBody responseBody = response.body();
            String responseContent = responseBody.string();
            if (!response.isSuccessful() || responseBody == null) {
                return  "";
            }

            JSONObject jsonObject = JSONObject.parseObject(responseContent);
            JSONArray itemsArray = jsonObject.getJSONArray("items");
            if (itemsArray == null || itemsArray.isEmpty()) {
                return "";
            }
            StringBuilder stringBuffer = new StringBuilder();
            for (int i = 0; i < itemsArray.size() && i < searchResultsLimit; i++) {
                JSONObject item = itemsArray.getJSONObject(i);
                stringBuffer.append(item.getString("snippet"));
                stringBuffer.append(item.getString("htmlSnippet"));
//                stringBuffer.append(resolveHtmlPage(item.getString("link")));
                stringBuffer.append("\r\n");
            }
            return stringBuffer.toString();

        }catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    private String resolveHtmlPage(String url) throws IOException {
        try{
            StringBuffer stringBuffer = new StringBuffer();
            URL u = new URL(url);
            BufferedReader reader = new BufferedReader(new InputStreamReader(u.openStream()));
            String input;
            while ((input = reader.readLine()) != null) {
                stringBuffer.append(input);
            }
            reader.close();
            return stringBuffer.toString();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

}
